<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>放大镜canvas版</title>
    <style type="text/css">
      * {
        margin: 0;
        padding: 0;
      }
      #canvas {
        display: block;
        margin: 0 auto;
        box-shadow: 2px 3px 10px 5px gray;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="477" height="476">
      <p>你的浏览器不支持Canvas</p>
    </canvas>
  </body>
  <script type="text/javascript">
    let canvas = document.getElementById("canvas");
    if (canvas.getContext) {
      let context = canvas.getContext("2d");
      // 创建图片
      let img = new Image();
      img.src = "./1.jpg";
      img.onload = function() {
        context.drawImage(img, 0, 0);
      };
      window.onresize = () => {
        let w =
          window.innerWidth ||
          document.documentElement.clientWidth ||
          document.body.clientWidth;
        let h =
          window.innerHeight ||
          document.documentElement.clientHeight ||
          document.body.clientHeight;

        canvas.width = w;
        canvas.height = h;

        // 清除画布
        context.clearRect(0, 0, canvas.width, canvas.height);
        // 再次绘制图片到画布上
        context.drawImage(img, 0, 0);
      };
      // 添加鼠标事件
      canvas.onmousedown = function() {
        console.log("canvas.width", canvas.width);
        console.log("canvas.height", canvas.height);
        canvas.onmousemove = function(e) {
          // 清除画布
          context.clearRect(0, 0, canvas.width, canvas.height);
          // 再次绘制图片到画布上
          context.drawImage(img, 0, 0);
          let event = window.event;
          let x = event.clientX - canvas.offsetLeft;
          let y = event.clientY - canvas.offsetTop;
          
          // 开始绘制放大区域
          context.drawImage(
            img,
            x - 50,
            y - 50,
            100,
            100,
            x - 70,
            y - 70,
            140,
            140
          );
        };
      };
      // 鼠标移出事件
      canvas.onmouseleave = function() {
        // 清除鼠标移动事件
        canvas.onmousemove = null;
        // 清除画布
        context.clearRect(0, 0, canvas.width, canvas.height);
        // 再次绘制图片到画布上
        context.drawImage(img, 0, 0);
      };
    } else {
      console.log("你的浏览器不支持Canvas!");
    }
  </script>
</html>
